package com.haoshuang.zhouzhoubang.ui.activity

import android.Manifest
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.provider.Settings
import android.widget.LinearLayout
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.haoshuang.zhouzhoubang.databinding.ActivityZsmBinding
import com.haoshuang.zhouzhoubang.model.bean.TeamLike
import com.haoshuang.zhouzhoubang.ui.adapter.TsAdapter
import com.haoshuang.zhouzhoubang.ui.dialog.Tis2Dialog
import com.haoshuang.zhouzhoubang.ui.vm.ZsmViewModel
import com.haoshuang.zhouzhoubang.utils.PaymentUtil
import com.haoshuang.zhouzhoubang.utils.PermissionHelper
import com.lxj.xpopup.XPopup
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.gone
import com.mufeng.libs.utils.view.load
import com.mufeng.libs.utils.view.visible
import java.io.FileNotFoundException
import java.io.IOException
import java.io.OutputStream


/**
 *  门店专属码
 */
class ZsmActivity : BaseVMActivity<ZsmViewModel, ActivityZsmBinding>() {

    lateinit var adapter: TsAdapter
    var list = arrayListOf<TeamLike>()

    override fun initIntent() {

    }

    override fun initView(savedInstanceState: Bundle?) {
        binding.appBar.ivBack.clickWithTrigger { finish() }
        binding.appBar.tvTitle.text = "门店专属码"
    }


    override fun initData() {

        vm.getData()
        adapter = TsAdapter(list)
        binding.apply {
            tvDy.visible()
            rvList.layoutManager = LinearLayoutManager(this@ZsmActivity)
            rvList.adapter = adapter
            tvShare.clickWithTrigger {
                type9 = 2
                PermissionHelper.requestPermission(
                    this@ZsmActivity,
                    "存储权限使用说明",
                    "用于快速保存分享图片",
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ) {
                    if (it) {
                        var bmp = getBitmap(llShare)
                        addBitmapToAlbum(this@ZsmActivity, bmp!!)
                    } else {
                        XPopup.Builder(this@ZsmActivity)
                            .asCustom(Tis2Dialog(this@ZsmActivity, "开启读写权限是为了保存图片") {
                                val intent = Intent()
                                intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                                intent.data = Uri.parse("package:" + getPackageName())
                                startActivity(intent)

                            })
                            .show()
                    }
                }
            }
            tvShare2.clickWithTrigger {
                type9 = 3
                PermissionHelper.requestPermission(
                    mActivity,
                    "存储权限使用说明",
                    "用于快速保存分享图片",
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ) {
                    if (it) {
                        var bmp = getBitmap(llShare)
                        addBitmapToAlbum(mActivity, bmp!!)
                    } else {
                        XPopup.Builder(mActivity)
                            .asCustom(Tis2Dialog(mActivity, "开启读写权限是为了保存图片") {
                                val intent = Intent()
                                intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                                intent.data = Uri.parse("package:" + getPackageName())
                                startActivity(intent)

                            })
                            .show()
                    }
                }
            }
        }
    }

    var type9 = 2
    fun getBitmap(view: LinearLayout): Bitmap? {
        view.isDrawingCacheEnabled = true
        view.buildDrawingCache() //启用DrawingCache并创建位图
        val bitmap =
            Bitmap.createBitmap(view.drawingCache) //创建一个DrawingCache的拷贝，因为DrawingCache得到的位图在禁用后会被回收
        view.isDrawingCacheEnabled = false //禁用DrawingCahce否则会影响性能
        return bitmap
    }

    fun addBitmapToAlbum(
        context: Context,
        bitmap: Bitmap
    ) {
        val displayName = "111jpg"
        val mimeType = "image/jpeg"
        val compressFormat = Bitmap.CompressFormat.JPEG

        val values = ContentValues()
        values.put(MediaStore.MediaColumns.DISPLAY_NAME, displayName)
        values.put(MediaStore.MediaColumns.MIME_TYPE, mimeType)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM)
        }
        val contentResolver = context.contentResolver
        val uri: Uri? = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
        if (uri != null) {
            var outputStream: OutputStream? = null
            try {
                outputStream = contentResolver.openOutputStream(uri)
                bitmap.compress(compressFormat, 100, outputStream)
                outputStream?.close()
                try {
                    when (type9) {

                        2 -> {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                                var phth = getFileUri(context, uri)
                                PaymentUtil.wxShareALl2(context, bitmap, false, phth)
                            } else {
                                PaymentUtil.wxShareALl2(
                                    context,
                                    bitmap,
                                    false,
                                    uri.path
                                )
                            }

                        }

                        3 -> {
                            ToastUtils.showShort("保存成功 ")

                        }
                    }

                } catch (e: Exception) {

                }
            } catch (e: FileNotFoundException) {
                e.printStackTrace()
            } catch (e: IOException) {
                e.printStackTrace()
            }
            if (outputStream != null) {
            }
        }
    }

    fun getFileUri(context: Context, contentUri: Uri): String? {
        // 授权给微信访问路径
        context.grantUriPermission(
            "com.tencent.mm",  // 这里填微信包名
            contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION
        )
        return contentUri.toString() // contentUri.toString() 即是以"content://"开头的用于共享的路径
    }

    override fun startObserve() {
        vm.getData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                if (it != null) {
                    binding.apply {
                        teamLogo.load(it.team_logo)
                        teamLogo2.load(it.team_logo)
                        qrcodeUrl.load(it.qrcode_url)
                        qrcodeUrl2.load(it.qrcode_url)
                        tvName.text = it.team_name
                        teamName.text = it.team_name
                        tvPhone.text = it.phone
                        tvPhone2.text = it.phone
                        list.clear()
                        for (b in it.team_like) {
                            if (!b.uid.isNullOrBlank()) {
                                list.add(b)
                            }
                        }
                        adapter.notifyDataSetChanged()
                    }

                }
            }
        }
    }

}